package com.tengits.react.amap3d;

import android.content.res.Resources;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableMap;

import java.util.ArrayList;

public class AMapUtils {
  public static int toPx(Float f) {
    return (int)(f * Resources.getSystem().getDisplayMetrics().density);
  }

  public static LatLng toLatLng(ReadableMap rm) {
    return new LatLng(rm.getDouble("latitude"), rm.getDouble("longitude"));
  }

  public static ArrayList<LatLng> toLatLngList(ReadableArray list) {
    ArrayList<LatLng> result = new ArrayList<>();
    for(int i = 0; i < list.size(); i++) {
      result.add(toLatLng(list.getMap(i)));
    }
    return result;
  }

  public static WritableMap toWritableMap(LatLng ll) {
    WritableMap map = Arguments.createMap();
    map.putDouble("latitude", ll.latitude);
    map.putDouble("longitude", ll.longitude);
    return map;
  }

  public static WritableMap toWritableMap(LatLngBounds llb) {
    WritableMap map = Arguments.createMap();
    map.putDouble("latitude", Math.abs((llb.southwest.latitude + llb.northeast.latitude) / 2));
    map.putDouble("longitude", Math.abs((llb.southwest.longitude + llb.northeast.longitude) / 2));
    map.putDouble("latitudeDelta", Math.abs(llb.southwest.latitude - llb.northeast.latitude));
    map.putDouble("longitudeDelta", Math.abs(llb.southwest.longitude - llb.northeast.longitude));
    return map;
  }

  public static LatLngBounds toLatLngBounds(ReadableMap rm) {
    Double latitude = rm.getDouble("latitude");
    Double longitude = rm.getDouble("longitude");
    Double latitudeDelta = rm.getDouble("latitudeDelta");
    Double longitudeDelta = rm.getDouble("longitudeDelta");
    return new LatLngBounds(
      new LatLng(latitude - latitudeDelta / 2, longitude - longitudeDelta / 2),
      new LatLng(latitude + latitudeDelta / 2, longitude + longitudeDelta / 2)
    );
  }
}
